package com.iims.market.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.iims.common.annotation.Log;
import com.iims.common.core.controller.BaseController;
import com.iims.common.core.domain.AjaxResult;
import com.iims.common.core.page.TableDataInfo;
import com.iims.common.enums.BusinessType;
import com.iims.market.domain.Contract;
import com.iims.market.service.IContractService;
import com.iims.market.vo.ContactRowVo;
import com.iims.market.vo.ContractContactorVo;
import com.iims.market.vo.ContractStats;
import com.iims.market.vo.GroupContractSearchQuery;
import com.iims.oder.vo.request.ContractFilingVo;
import io.swagger.annotations.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;

/**
 * @author fanpei
 * @date 2021/6/16 16:16
 */
@Api(tags = "H-合同管理")
@RestController
@RequestMapping("/business/contract")
public class ContractController extends BaseController {

    @Autowired
    private IContractService contractService;

    /**
     * 获取合同列表
     */
    @ApiOperation(value = "[高级搜索] 分页获取合同列表", response = ContactRowVo.class)
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "当前记录起始索引(从1开始)", name = "pageNum", paramType = "query", required = true),
            @ApiImplicitParam(value = "每页显示记录数（>0）", name = "pageSize", paramType = "query", required = true),
            @ApiImplicitParam(value = "排序列", name = "orderByColumn", paramType = "query"),
            @ApiImplicitParam(value = "升降序方式：0升序 1降序", name = "isAsc", paramType = "query"),
            @ApiImplicitParam(value = "创建开始时间:format = \"yyyy-MM-dd\"", name = "beginTime", paramType = "query"),
            @ApiImplicitParam(value = "创建结束时间:format = \"yyyy-MM-dd\"", name = "endTime", paramType = "query"),
            @ApiImplicitParam(value = "合同类型:精确匹配", name = "ctraTypeId", paramType = "query"),
            @ApiImplicitParam(value = "客户类型：精确匹配", name = "customerId", paramType = "query"),
            @ApiImplicitParam(value = "合同名称:模糊匹配", name = "contractName", paramType = "query"),
            @ApiImplicitParam(value = "合同编号:模糊匹配", name = "contractCode", paramType = "query"),
            @ApiImplicitParam(value = "销售人员:模糊匹配", name = "sellUser", paramType = "query")
    })
    @PreAuthorize("@ss.hasPermi('business:contract:list')")
    @GetMapping("/list")
    public TableDataInfo list(@ApiIgnore Contract contract) throws Exception {
        startPage();
        setSearchTimeRange(contract);
        setSeqNumPageSizeStart(contract);
        List<ContactRowVo> list = contractService.selectContractList(contract);
        return getDataTable(list);
    }

    @ApiOperation(value = "[高级搜索] 合同统计数据", response = ContractStats.class)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "创建开始时间:format = \"yyyy-MM-dd\"", name = "beginTime", paramType = "query"),
            @ApiImplicitParam(value = "创建结束时间:format = \"yyyy-MM-dd\"", name = "endTime", paramType = "query"),
            @ApiImplicitParam(value = "合同类型:精确匹配", name = "ctraTypeId", paramType = "query"),
            @ApiImplicitParam(value = "客户类型：精确匹配", name = "customerId", paramType = "query"),
            @ApiImplicitParam(value = "合同名称:模糊匹配", name = "contractName", paramType = "query"),
            @ApiImplicitParam(value = "合同编号:模糊匹配", name = "contractCode", paramType = "query"),
            @ApiImplicitParam(value = "销售人员:模糊匹配", name = "sellUser", paramType = "query")
    })
    @ApiOperationSupport(order = 2)
    @PreAuthorize("@ss.hasPermi('business:contract:list')")
    @GetMapping("/stats")
    public AjaxResult stats(@ApiIgnore Contract contract) throws Exception {
        setSearchTimeRange(contract);
        return AjaxResult.success(contractService.selectContractStat(contract));
    }

    /**
     * [分组搜索] 获取合同列表
     */
    @ApiOperation(value = "[分组搜索] 分页获取合同列表", notes = "按钮分组顺序：scopeValue、typeValue、timeValue", response = ContactRowVo.class)
    @ApiOperationSupport(order = 3)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "当前记录起始索引(从1开始)", name = "pageNum", paramType = "query", required = true),
            @ApiImplicitParam(value = "每页显示记录数（>0）", name = "pageSize", paramType = "query", required = true),
            @ApiImplicitParam(value = "排序列", name = "orderByColumn", paramType = "query"),
            @ApiImplicitParam(value = "升降序方式：0升序 1降序", name = "isAsc", paramType = "query"),
            @ApiImplicitParam(value = "综合模糊搜索:合同名/合同编号/合同类型/客户名/销售负责人", name = "searchValue", paramType = "query")
    })
    @PreAuthorize("@ss.hasPermi('business:contract:list')")
    @GetMapping("/groupList")
    public TableDataInfo groupList(GroupContractSearchQuery groupSearchQuery) throws Exception {
        startPage();
        setSeqNumPageSizeStart(groupSearchQuery);
        return getDataTable(contractService.selectContractListByGroup(groupSearchQuery));
    }

    @ApiOperation(value = "[分组搜索] 合同统计数据", response = ContractStats.class)
    @ApiImplicitParam(value = "综合模糊搜索:合同名/合同编号/合同类型/客户名/销售负责人", name = "searchValue", paramType = "query")
    @ApiOperationSupport(order = 4)
    @PreAuthorize("@ss.hasPermi('business:contract:list')")
    @GetMapping("/groupStats")
    public AjaxResult stats(GroupContractSearchQuery groupSearchQuery) {
        setSeqNumPageSizeStart(groupSearchQuery);
        return AjaxResult.success(contractService.selectContractStatsByGroup(groupSearchQuery));
    }


    /**
     * 根据合同编号获取详细信息
     */
    @ApiOperation(value = "根据合同id获取合同详情", response = ContactRowVo.class)
    @ApiOperationSupport(order = 5)
    @ApiImplicitParam(name = "contractId", value = "合同id", required = true, paramType = "query")
    @PreAuthorize("@ss.hasPermi('business:contract:query')")
    @GetMapping(value = "/{contractId}")
    public AjaxResult getInfo(@PathVariable Long contractId) {
        return AjaxResult.success(contractService.selectDetailById(contractId));
    }

    /**
     * 新增合同
     */
    @ApiOperation(value = "新增合同", notes = "【腾讯文档】合同-baseReq字段说明\n" +
            "https://docs.qq.com/sheet/DUHNiVm9aVVpOeHZJ?tab=BB08J2")
    @ApiOperationSupport(
            ignoreParameters = {"contractId", "ctraTypeName", "customerName", "sellUser",
                    "bigStatus", "fileStatus", "reallyDeliveryDate", "fileCode", "fileLocation"})
    @PreAuthorize("@ss.hasPermi('business:contract:add')")
    @Log(title = "合同管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody Contract contract) {
        return toAjax(contractService.insertContract(contract));
    }

    /**
     * 修改合同
     */
    @ApiOperation("修改合同")
    @ApiOperationSupport(
            ignoreParameters = {"contractId", "ctraTypeName", "customerName", "sellUser",
                    "bigStatus", "fileStatus", "reallyDeliveryDate", "fileCode", "fileLocation"})
    @PreAuthorize("@ss.hasPermi('business:contract:edit')")
    @Log(title = "合同管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody Contract contract) {
        return toAjax(contractService.updateContract(contract));
    }

    /**
     * 删除合同
     */
    @ApiOperation("删除合同")
    @PreAuthorize("@ss.hasPermi('business:contract:remove')")
    @Log(title = "合同管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{contractId}")
    public AjaxResult remove(@ApiParam("合同Id") @PathVariable Long contractId) {
        return toAjax(contractService.deleteContractById(contractId));
    }

    /**
     * 合同归档
     */
    @ApiOperation("更新合同归档信息")
    @PreAuthorize("@ss.hasPermi('business:contract:edit')")
    @Log(title = "合同管理", businessType = BusinessType.UPDATE)
    @PutMapping("/filling")
    public AjaxResult edit(@Validated @RequestBody ContractFilingVo contractFilingVo) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(contractFilingVo, contract);
        return toAjax(contractService.fillingContract(contract));
    }

    @ApiOperation(value = "获取合同收货人信息", response = ContractContactorVo.class)
    @Log(title = "合同管理", businessType = BusinessType.UPDATE)
    @PutMapping("/consignee/{contractId}")
    public AjaxResult edit(@ApiParam("合同id") @PathVariable Long contractId) {
        return AjaxResult.success(contractService.selectContractContator(contractId));
    }
}
